我正在尝试使用Apache Java LIB 4.3.2进行POST类型的HttpRequest,我遇到了问题。
没有方法可以将主体设置为参数值......
我正在尝试在post http请求的主体上设置flac二进制文件。
以下是我的示例代码:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class GoogleSpeech {
/**
* @param args
*/
public static void main(String[] args) {
try {
HttpClient client = new DefaultHttpClient();
String getURL = "https://www.google.com/speech-api/v1/recognize?client=chromium&lang=pt-PT&maxresults=10";
HttpPost get = new HttpPost(getURL);
get.setHeader("Content-Type", " audio/x-flac; rate=16000;");
get.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.77 Safari/535.7");
HttpResponse responseGet = client.execute(get);
System.out.println(responseGet);
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:3)
我不知道我是否正确地提出了你的问题,但如果你想将参数设置为HttpPost实例,那么这是怎么做的。
我复制了你的第一部分,即使我发现有点噱头叫“获取”HttpPost的一个实例:)
String getURL = "https://www.google.com/speech-api/v1/recognize?client=chromium&lang=pt-PT&maxresults=10";
HttpPost get = new HttpPost(getURL);
get.setHeader("Content-Type", " audio/x-flac; rate=16000;");
get.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.77 Safari/535.7");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("param1", "paramValue1")); // name and value of your param
formparams.add(new BasicNameValuePair("param2", paramValue2)); // name and value of your param
// and so on
// create the encoded form
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
// set it in the post request
get.setEntity(entity);
如果您需要上传二进制文件,则可以使用MultipartEntity代替UrlEncodedFormEntity。它有一个addPart方法,可用于二进制blob。我没有尝试过这一行,但它应该类似于:
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", new FileBody(new File("your path here")));