我正在尝试进行开机自检连接,但它不起作用。错误是"连接超时"。 我发送一个字符串并接收另一个字符串,post参数是"quest"。 服务器工作正常。我已经完成了上传用于 POST 连接的站点的测试,并且一切正常。我认为问题出在安卓方面,因为这是我第一次尝试进行 POST 连接。
此外,服务器端是 Node.js通过调用/search 进行 Express 框架处理。
这是Java代码:
public class DownloadDados extends AsyncTask<String, Void, String> {
public static final String REQUEST_METHOD = "POST";
public static final int READ_TIMEOUT = 20000;
//public static final String charset = "UTF-8";
public static final int CONNECTION_TIMEOUT = 20000;
@Override
protected void onPreExecute(){
//Log.i(TAGAsync, "ON PRE EXECUTE");
//Toast.makeText(TAGAs,"Buscando Servidor", Toast.LENGTH_LONG).show();
}
@Override
protected String doInBackground(String... params) {
// params[0] an string
String stringUrl = "http://XXX.XXX.XX.XX:3000/search"; //blocked for security reasons
String quest = "quest="+params[0]; //enter the parameter
int responseCode = 0;
String result;
String inputLine;
try{
URL myUrl = new URL(stringUrl);
HttpURLConnection connection =(HttpURLConnection) myUrl.openConnection();
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setRequestProperty("Accept-Charset", "UTF-8");
//connection.connect();
String urlParameters = URLEncoder.encode(quest, "UTF-8");
connection.setDoOutput(true);
DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
dStream.writeBytes(urlParameters);
dStream.flush();
dStream.close();
responseCode = connection.getResponseCode();
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
result = stringBuilder.toString();
}
catch(IOException e){
Log.i(TAGAsync, "URL: "+ stringUrl + " Error: " + e.getMessage() + " responseCode: " + responseCode);
//Toast.makeText(TAGAs,"Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
result = null;
}
return result;
}
我想知道错误是否在我的 Java 代码上。有人可以帮忙吗?
编辑:
05/16 21:39:03: Launching app
$ adb install-multiple -r -t -p com.bizzo.speech4beef C:UsersBizzoAndroidStudioProjectsSpeech4Beefappbuildintermediatessplit-apkdebugslicesslice_1.apk
Split APKs installed
$ adb shell am start -n "com.bizzo.speech4beef/com.bizzo.speech4beef.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Connected to process 23492 on device asus-asus_x00ld-HAAXB602M664EG3
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
W/System: ClassLoader referenced unknown path: /data/app/com.bizzo.speech4beef-1/lib/arm64
I/InstantRun: starting instant run server: is main process
V/Monotype: SetAppTypeFace- try to flip, app = com.bizzo.speech4beef
V/Monotype: Typeface getFontPathFlipFont - systemFont = default#default
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
V/Monotype: SetAppTypeFace- try to flip, app = com.bizzo.speech4beef
Typeface getFontPathFlipFont - systemFont = default#default
V/BoostFramework: mAcquireFunc method = public int com.qualcomm.qti.Performance.perfLockAcquire(int,int[])
mReleaseFunc method = public int com.qualcomm.qti.Performance.perfLockRelease()
mAcquireTouchFunc method = public int com.qualcomm.qti.Performance.perfLockAcquireTouch(android.view.MotionEvent,android.util.DisplayMetrics,int,int[])
V/BoostFramework: mIOPStart method = public int com.qualcomm.qti.Performance.perfIOPrefetchStart(int,java.lang.String)
mIOPStop method = public int com.qualcomm.qti.Performance.perfIOPrefetchStop()
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@c812720
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@fa998d9
W/AbstractGoogleClient: Application name is not set. Call Builder#setApplicationName.
I/Adreno: QUALCOMM build : c5b7903, Ic4cf336e0a
Build Date : 02/17/17
OpenGL ES Shader Compiler Version: XE031.09.00.04
Local Branch :
Remote Branch :
Remote Branch :
Reconstruct Branch :
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@901f80d
I/DpmTcmClient: RegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/AsyncTask: URL: http://<--ComputerIP-->:3000/search Error: Connection timed out responseCode: 0
I/AsyncTask: Error to download data: main
这是我刚刚从全功能代码中获取的一个工作示例,所以这应该可以工作。
只需创建一个方法来处理您的请求:
public String makeHttpRequest(Map<String, String> params){
String result = "";
InputStream responseStream = null;
String logMess = "";
long startTime;
long stopTime;
long elapsedTime;
try {
startTime = System.currentTimeMillis();
StringBuilder postData = new StringBuilder();
for(Map.Entry<String, String> param : params.entrySet()){
if(postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
//This should be addressing some script like PHP something like search.php
String stringUrl = "http://XXX.XXX.XX.XX:3000/search";
URL myUrl = new URL(stringUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
DataOutputStream request = new DataOutputStream(conn.getOutputStream());
request.write(postDataBytes);
request.flush();
request.close();
//Check the response code of the server -
Integer replyCode = conn.getResponseCode();
logMess += " Reply Code: " + replyCode.toString();
responseStream = new BufferedInputStream(conn.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
stopTime = System.currentTimeMillis();
elapsedTime = stopTime - startTime;
logMess += " elapsed Time : " + elapsedTime + " ms";
// Of course you do not need to do a time measurement, but it might be interesting
Log.d(TAG, "makeHttpRequest --- " + logMess);
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("n");
}
responseStreamReader.close();
result = stringBuilder.toString();
}
catch (UnsupportedEncodingException e) {
Log.e(TAG, "makeHttpRequest --- " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "makeHttpRequest --- " + e.getMessage());
}
return result;
}
现在只需从AsyncTask
或后台线程中调用该方法makeHttpRequest()
,如下所示:
Map<String, String> paramList = new LinkedHashMap<String, String>();
paramList.put("quest", params[0]);
String requestResult = makeHttpRequest(paramList);
.
注意:方法makeHttpRequest()
必须从AsyncTask
或后台线程调用,否则会出现错误!
.
另请注意,您的"stringUrl"应该指向一些脚本,例如PHP!