gpt4 book ai didi

android - 如何使用 NameValuePair 发送字节 HTTP?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:33:46 35 4
gpt4 key购买 nike

我想使用这个 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
}
}

不幸的是,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();
}

在此示例中,我发布了一个图像 (jpg) 和字符串,您可以在此处下载多部分发布库:http://hc.apache.org/downloads.cgibm 是位图。您还可以使用:

Bundle bundle=new Bundle();
bundle.putString("key", "value");
byte[] b = bundle.getByteArray("key");
ByteArrayBody bab = new ByteArrayBody(b,"info");

关于android - 如何使用 NameValuePair 发送字节 HTTP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9212082/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com