我想使用此NameValuePair方法从我的Android客户端向Web服务器发送几个值:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http:/xxxxxxx");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
String amount = paymentAmount.getText().toString();
String email = inputEmail.getText().toString();
nameValuePairs.add(new BasicNameValuePair("donationAmount", amount));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("paymentMethod", "5"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,NameValuePair只能发送String,我也需要发送byte []值.有人可以帮我解决我的问题吗?
HttpPost httppost = new HttpPost("http://upload-test.php");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
HttpClient httpClient = new DefaultHttpClient();
if(bm!=null){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data, name+".jpg");
entity.addPart("file", bab);
}
try {
StringBody sname = new StringBody(name);
entity.addPart("name", sname);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
httppost.setEntity(entity);
try {
httpClient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我发布了一个Image(jpg)和String,你可以在这里下载多部分的帖子库:http://hc.apache.org/downloads.cgi bm是一个Bitmap.你也可以使用:
Bundle bundle=new Bundle();
bundle.putString("key", "value");
byte[] b = bundle.getByteArray("key");
ByteArrayBody bab = new ByteArrayBody(b,"info");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10178 次 |
| 最近记录: |