我正在尝试使用 httpclient 在 android 中获取 cURL 请求。
curl -k -X POST \
-F 'image=@00001_1.png;type=image/png' \
-F 'svgz=@00001_1.png;type=image/svg+xml' \
-F 'json={
"text" : "Hello world!",
"tid" : "0010",
"timestamp" : "1342683312",
"location" : [ 22793, -553.3344],
"facebook" :
{
"id": "4444444",
"access_token": "7FUinHfxsCTrx",
"expiration_date": "1358204400"
}
};type=application/json' \
https://example.com/api/posts
这是给我一个来自服务器的错误请求错误(400)的代码。
public static void example() {
HttpClient client = getNewHttpClient();
HttpPost httpost = new HttpPost("https://example.com/api/posts");
httpost.addHeader("image", "@00001_1.png; type=image/png");
httpost.addHeader("svgz", "@00001_1.png; type=image/svg+xml");
httpost.addHeader("type", "multipart/form-data");
// httpost.setHeader("Content-type", "multipart/form-data");
JSONObject data = new JSONObject();
JSONObject facebook = new JSONObject();
JSONArray location = new JSONArray();
HttpResponse response = null;
try {
data.put("text","Hello world!");
data.put("templateid","0010");
data.put("timestamp","2012-07-08 09:00:45.312195368+00:00");
location.put(37.7793);
location.put(-122.4192);
data.put("location", location);
facebook.put("id", "4444444");
facebook.put("access_token", "7FUinHfxsCTrx");
facebook.put("expiration_date", "1358204400");
data.put("facebook", facebook);
System.out.println(" ---- data ----- "+data);
StringEntity stringEntity = new StringEntity(data.toString(), "utf-8");
httpost.setEntity(stringEntity);
try {
response = client.execute(httpost);
System.out.println(" --- response --- "+response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if(entity != null) {
// A Simple Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
System.out.println(" ---- result ---- "+result);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
它从命令行完美运行,不要在哪里出错。任何帮助高度赞赏。
也让我知道我是否可以在不使用任何用 C 编写的库(Libcurl 等)的情况下做到这一点。
谢谢。