【发布时间】:2018-10-27 02:43:21
【问题描述】:
我正在尝试进行 POST 连接,但它不起作用。错误是“连接超时”。 我发送一个字符串并接收另一个字符串,post 参数是“quest”。 服务器工作正常。我已经完成了为 POST 连接上传站点的测试,并且一切正常。我认为问题出在 android 端,因为这是我第一次尝试进行 POST 连接。
服务器端也是 Node.js,使用 Express 框架处理 /search 调用。
这是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:\Users\Bizzo\AndroidStudioProjects\Speech4Beef\app\build\intermediates\split-apk\debug\slices\slice_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
【问题讨论】:
-
能否请您发布来自您的客户端代码的堆栈跟踪?
-
切换到
Retrofit会让您的任务更轻松。 -
是的,我知道改造会容易得多,但我想先学习这种方法。
-
我认为您的参数可能编码错误。假设“params[0] 包含一个字符串“tom”,那么您将是 urlParameters = “quest%3Dtom”,但您想要的可能是“quest=tom”。所以您需要像这样对每个部分进行编码:: String part1 = URLEncoder.encode("quest", "UTF-8"); String part2 = URLEncoder.encode(params[0], "UTF-8"); 然后 String urlParameters = part1 + "=" + part2;
-
尝试将超时设置得更长,例如 READ_TIMEOUT = 60000;和 CONNECTION_TIMEOUT = 60000;
标签: java android post httpconnection