从Android我想用POST方法调用API
当我提交来自邮递员的请求时,我得到了API的响应,如图所示 screenshot1.jpg=我需要传递的数据 screenshot2.jpg=我们得到的结果 我试着用下面的代码通过安卓系统给他们打电话,但不起作用从Android我想用POST方法调用API,android,api,post,Android,Api,Post,当我提交来自邮递员的请求时,我得到了API的响应,如图所示 screenshot1.jpg=我需要传递的数据 screenshot2.jpg=我们得到的结果 我试着用下面的代码通过安卓系统给他们打电话,但不起作用 JSONObject login = new JSONObject(); login.put("username", userName); login.put("password", password); login.put("platform", "ANDROID"); logi
JSONObject login = new JSONObject();
login.put("username", userName);
login.put("password", password);
login.put("platform", "ANDROID");
login.put("location", "56.1603092,10.2177147");
String str = WebServices.excutePost(url, login);
public static String excutePost(String targetURL, JSONObject urlParameters) {
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/raw");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.toString().getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
OutputStream out = new BufferedOutputStream(connection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(String.valueOf(urlParameters.toString().getBytes("UTF-8")));
out.close();
//connection.disconnect();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
您可以使用以下方法:
public String executePost(String targetURL,String urlParameters) {
int timeout=5000;
URL url;
HttpURLConnection connection = null;
try {
// Create connection
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/json");
connection.setRequestProperty("Content-Length",
"" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
// Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (SocketTimeoutException ex) {
ex.printStackTrace();
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
您可以创建URL参数,如:
JSONObject loginParams = new JSONObject();
loginParams .put("username", userName);
loginParams .put("password", password);
loginParams .put("platform", "ANDROID");
loginParams .put("location", "56.1603092,10.2177147");
调用如下方法:
executePost(serviceURL,loginParams.toString());
您可以使用以下方法:
public String executePost(String targetURL,String urlParameters) {
int timeout=5000;
URL url;
HttpURLConnection connection = null;
try {
// Create connection
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/json");
connection.setRequestProperty("Content-Length",
"" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
// Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (SocketTimeoutException ex) {
ex.printStackTrace();
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
您可以创建URL参数,如:
JSONObject loginParams = new JSONObject();
loginParams .put("username", userName);
loginParams .put("password", password);
loginParams .put("platform", "ANDROID");
loginParams .put("location", "56.1603092,10.2177147");
调用如下方法:
executePost(serviceURL,loginParams.toString());
您可以使用该库更容易地实现与REST服务的网络通信
顺便说一下,您可以尝试我的解决方案来解决您的问题:
- 首先创建一个executeHttp方法
private JSONObject executeHttp(HttpUriRequest request, Context context) throws ClientProtocolException, IOException { HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 10000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient client = new DefaultHttpClient(httpParameters); // add your header in here - I saw your header has 7 params request.addHeader("Authorization", getToken()); request.addHeader("APIKey", API_KEY); request.addHeader("Content-Type", "application/x-www-form-urlencoded"); request.addHeader("X-Request-Mime-Type", "application/json;"); HttpResponse execute = client.execute(request); InputStream content = execute.getEntity().getContent(); // implement your handle response here, below is just an example try { return new JSONObject().put("content", this.convertStreamToByteArray(content)); } catch (JSONException e) { //Crashlytics.logException(e); Log.e(LOG_TAG, "Error converting stream to byte array: " + e.getMessage()); return new JSONObject(); } }
public JSONObject doPost(List<NameValuePair> headerParams, List<NameValuePair> parameters, String url, Context context) throws ClientProtocolException, IOException {
HttpPost httpPost = new HttpPost(url);
// add the header if needed
if (headerParams != null) {
for (NameValuePair headerParam: headerParams) {
httpPost.addHeader(headerParam.getName(), headerParam.getValue());
}
}
httpPost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
return executeHttp(httpPost, context);
}
使用nameValuePairs创建的
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", userName));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("platform", "ANDROID"));
nameValuePairs.add(new BasicNameValuePair("location", "56.1603092,10.2177147"));
List nameValuePairs=new ArrayList();
添加(新的BasicNameValuePair(“用户名”,username));
添加(新的BasicNameValuePair(“密码”,password));
添加(新的BasicNameValuePair(“平台”、“ANDROID”);
添加(新的BasicNameValuePair(“位置”,“56.1603092,10.2177147”);
您可以使用库来更轻松地实现与REST服务的网络通信
顺便说一下,您可以尝试我的解决方案来解决您的问题:
- 首先创建一个executeHttp方法
private JSONObject executeHttp(HttpUriRequest request, Context context) throws ClientProtocolException, IOException { HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 10000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient client = new DefaultHttpClient(httpParameters); // add your header in here - I saw your header has 7 params request.addHeader("Authorization", getToken()); request.addHeader("APIKey", API_KEY); request.addHeader("Content-Type", "application/x-www-form-urlencoded"); request.addHeader("X-Request-Mime-Type", "application/json;"); HttpResponse execute = client.execute(request); InputStream content = execute.getEntity().getContent(); // implement your handle response here, below is just an example try { return new JSONObject().put("content", this.convertStreamToByteArray(content)); } catch (JSONException e) { //Crashlytics.logException(e); Log.e(LOG_TAG, "Error converting stream to byte array: " + e.getMessage()); return new JSONObject(); } }
public JSONObject doPost(List<NameValuePair> headerParams, List<NameValuePair> parameters, String url, Context context) throws ClientProtocolException, IOException {
HttpPost httpPost = new HttpPost(url);
// add the header if needed
if (headerParams != null) {
for (NameValuePair headerParam: headerParams) {
httpPost.addHeader(headerParam.getName(), headerParam.getValue());
}
}
httpPost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
return executeHttp(httpPost, context);
}
使用nameValuePairs创建的
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", userName));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("platform", "ANDROID"));
nameValuePairs.add(new BasicNameValuePair("location", "56.1603092,10.2177147"));
List nameValuePairs=new ArrayList();
添加(新的BasicNameValuePair(“用户名”,username));
添加(新的BasicNameValuePair(“密码”,password));
添加(新的BasicNameValuePair(“平台”、“ANDROID”);
添加(新的BasicNameValuePair(“位置”,“56.1603092,10.2177147”);
问题是使用stringbuffer类,我使用string获得响应,它工作得非常好。谢谢大家的评论和回答。问题是使用stringbuffer类,我使用string获得响应,它工作得非常好。谢谢大家的评论和回答。你能详细说明一下“不工作”吗?它在做什么或不做什么?是否有错误消息?我认为您的内容类型应该是application/jsonce如果可能的话,您可以为问题提供stacktrace吗?您是否尝试过output.writeBytes(String.valueOf(urlParameters.toString().getBytes(“UTF-8”);你能详细说明一下“不工作”吗?它在做什么或不做什么?是否有错误消息?我认为您的内容类型应该是application/jsonce如果可能的话,您可以为问题提供stacktrace吗?您是否尝试过output.writeBytes(String.valueOf(urlParameters.toString().getBytes(“UTF-8”);