我在Android中使用了HttpPost和HttpURLConnection来发送带有以下标题和内容的请求:
接头: api_key:9a8akx8badkaxxxx, 速度:0, 声音:男, 韵律:1, 缓存控制:无缓存
内容(包含Content-Type:text / plain): 大家好,
这些是我的代码: *使用HttpPost:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(requestURL);
post.addHeader("api_key", "9a8akx8badkaxxxx");
post.addHeader("speed", "0");
post.addHeader("voice", "male");
post.addHeader("prosody", "1");
post.addHeader("Cache-Control", "no-cache");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("data[body]", "Hello everyone"));
AbstractHttpEntity ent= null;
ent = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
ent.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
ent.setContentEncoding("UTF-8");
post.setEntity(ent);
post.setURI(new URI("http://api.openfpt.vn/text2speech/v4"));
HttpResponse response =client.execute(post);
*使用HttpURLConnection:
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("api_key", "9a8akx8badkaxxxx");
conn.setRequestProperty("Content-Type", "text/plain");
conn.setRequestProperty("speed", "0");
conn.setRequestProperty("voice", "male");
conn.setRequestProperty("prosody", "1");
conn.setRequestProperty("Cache-Control", "no-cache");
然后我不知道将内容“Hello everyone”放入HttpURLConnection的方法
结果始终错误。但是当我在Firefox中使用附加的HttpRequester时,响应是可以的。 请帮我在Android中创建和设置Http请求
答案 0 :(得分:0)
尝试此设置内容类型:
HttpPost httppost = new HttpPost(builder.getUrl());
httppost.setHeader(HTTP.CONTENT_TYPE,
"text/plain;charset=UTF-8");
要设置任意标头,我相信应该这样做:
httppost.setHeader("api_key", "9a8akx8badkaxxxx");
httppost.setHeader("speed", "0");
httppost.setHeader("voice", "male");
httppost.setHeader("voice", "male");
httppost.setHeader("prosody", "1");
httppost.setHeader("Cache-Control", "no-cache");
要发送数据,请选择帖子字段的名称(此处为Fn和IdDevice):
List<NameValuePair> nameValuePairs = new ArrayList<>(1);
// nameValuePairs.add(new BasicNameValuePair("Fn",function));
// nameValuePairs.add(new BasicNameValuePair("IdDevice",IdDevice));
编辑开始
nameValuePairs.add(new BasicNameValuePair("Content","Hello everyone"));
编辑结束
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
最后,执行帖子请求:
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);