我遇到了post方法的一些问题:似乎没有将数据添加到请求中。我的json对象(下面的jObject)是{"FirstName":"John"}
,但响应是{"FirstName":"Peter"}
。为什么POST不能处理此请求?
@Override
protected Void doInBackground(Void... arg) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(someUrl);
ResponseHandler <String> responseHandler = new BasicResponseHandler();
request.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(jObject.toString());
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
request.setEntity(se);
String authorizationString = "Basic " + Base64.encodeToString(("username" + ":" + "password").getBytes(), Base64.NO_WRAP);
request.addHeader("Authorization", authorizationString);
String response = httpClient.execute(request, responseHandler);
编辑:我最初检索数据的方式
// Initialize url and create connection
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
byte[] auth = (email_login + ":" + password_login).getBytes();
String basic = Base64.encodeToString(auth, Base64.NO_WRAP);
httpConn.setRequestProperty("Authorization", "Basic " + basic);
// Retrieve data
try{
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = connection.getInputStream();
if(connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
return out.toByteArray();
} finally {
connection.disconnect();
}
答案 0 :(得分:1)
尝试设置以UTF8字节数组编码的json数据,如下所示:
request.setEntity(new ByteArrayEntity(
postMessage.toString().getBytes("UTF8")));
这适合我......