我想向需要身份验证的服务器生成POST请求。我尝试使用以下方法:
private synchronized String CreateNewProductPOST (String urlString, String encodedString, String title, String content, Double price, String tags) {
String data = "product[title]=" + URLEncoder.encode(title) +
"&product[content]=" + URLEncoder.encode(content) +
"&product[price]=" + URLEncoder.encode(price.toString()) +
"&tags=" + tags;
try {
URL url = new URL(urlString);
URLConnection conn;
conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encodedString);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
return rd.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
return e.getMessage();
}
catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
}
但服务器未收到授权数据。应该添加授权数据的行如下:
conn.setRequestProperty ("Authorization", "Basic " + encodedString);
和行
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
也会抛出IOException。
无论如何,如果有人建议修改上述逻辑以便使用带有UrlConnection的POST启用授权,我将非常感激。
但显然它不能正常工作,尽管如果GET请求使用相同的逻辑,一切正常。
答案 0 :(得分:40)
罚款example found here。 Powerlord说得对,below,对于POST,您需要HttpURLConnection
,而不是。{/ p>
以下是执行该操作的代码,
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty ("Authorization", encodedCredentials);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(data);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
将URLConnection
更改为HttpURLConnection
,以使其成为POST请求。
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
建议(......在评论中):
您可能还需要设置这些属性,
conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );
答案 1 :(得分:10)
我没有在代码中看到您指定这是POST请求的任何地方。然后,你需要一个java.net.HttpURLConnection
来做到这一点。
事实上,我强烈建议您使用HttpURLConnection
代替URLConnection
和conn.setRequestMethod("POST");
,并查看它是否仍然存在问题。
答案 2 :(得分:4)
对外部应用程序执行oAuth身份验证(INSTAGRAM)步骤3“收到代码后获取令牌”仅下面的代码为我工作
值得说明的是,我使用一些localhost URL和一个回调servlet配置了名称“web.xml中的回调和回调URL注册:例如localhost:8084 / MyAPP / docs / insta / callback
但是在成功完成身份验证步骤之后,使用相同的外部站点“INSTAGRAM”来执行GET标记或MEDIA以使用初始方法检索JSON数据不起作用。 在我的servlet中使用url做GET 例如api.instagram.com/v1/tags/MYTAG/media/recent?access_token=MY_TOKEN找到HERE的唯一方法
感谢所有贡献者
URL url = new URL(httpurl);
HashMap<String, String> params = new HashMap<String, String>();
params.put("client_id", id);
params.put("client_secret", secret);
params.put("grant_type", "authorization_code");
params.put("redirect_uri", redirect);
params.put("code", code); // your INSTAGRAM code received
Set set = params.entrySet();
Iterator i = set.iterator();
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> param : params.entrySet()) {
if (postData.length() != 0) {
postData.append('&');
}
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
reader.close();
conn.disconnect();
System.out.println("INSTAGRAM token returned: "+builder.toString());
答案 3 :(得分:2)
发送POST请求呼叫:
connection.setDoOutput(true); // Triggers POST.
如果要在请求中发送文本,请使用:
java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(connection.getOutputStream());
wr.write(textToSend);
wr.flush();
答案 4 :(得分:1)
我今天遇到了这个问题,这里发布的解决方案都没有奏效。但是,发布的代码here适用于 POST 请求:
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
事实证明,这不是授权问题。就我而言,这是一个编码问题。我需要的内容类型是 application / json ,但是来自Java文档:
static String encode(String s, String enc)
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.
encode函数将字符串转换为 application / x-www-form-urlencoded 。
现在,如果您未设置内容类型,则可能会收到415不支持的媒体类型错误。如果将其设置为 application / json 或任何不是 application / x-www-form-urlencoded 的内容,则会出现IOException。要解决此问题,只需避免使用编码方法。
对于此特定方案,以下内容应该有效:
String data = "product[title]=" + title +
"&product[content]=" + content +
"&product[price]=" + price.toString() +
"&tags=" + tags;
在创建缓冲读取器时代码中断原因可能有用的另一小部分信息是因为 POST 请求实际上只在 conn.getInputStream()强>被称为。
答案 5 :(得分:1)
在API 22上对BasicNamevalue对的使用进行了描述,而不是使用HASMAP。要了解有关HasMap的更多信息,请访问more on hasmap developer.android
******************************************************************************
Starting task: Build solution $/Root/TestApi/Development/TestApi.sln
******************************************************************************
Executing the powershell script: C:\LR\MMS\Services\Mms\TaskAgentProvisioner\Tools\tasks\VSBuild\1.0.13\VSBuild.ps1
C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe "C:\a\dce2e497\Root\TestApi.sln" /nologo /m /nr:false /fl /flp:"logfile=C:\a\dce2e497\Root\TestApi.sln.log" /dl:CentralLogger,"C:\LR\MMS\Services\Mms\TaskAgentProvisioner\Tools\agent\worker\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll"*ForwardingLogger,"C:\LR\MMS\Services\Mms\TaskAgentProvisioner\Tools\agent\worker\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll" /p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="C:\a\dce2e497\staging" /p:platform="any cpu" /p:configuration="release" /p:VisualStudioVersion="14.0"
Build started 8/2/2015 11:21:29 AM.
1>Project "C:\a\dce2e497\Root\TestApi.sln" on node 1 (default targets).
1>ValidateSolutionConfiguration:
Building solution configuration "release|any cpu".
1>Project "C:\a\dce2e497\Root\TestApi.sln" (1) is building "C:\a\dce2e497\Root\TestApi.Api\TestApi.Api.xproj" (2) on node 1 (default targets).
2>PrepareForBuild:
Creating directory "..\artifacts\bin\TestApi.Api\".
Creating directory "..\artifacts\obj\TestApi.Api\Release\".
PreComputeCompileTypeScript:
C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.4\tsc.exe --noEmitOnError COMPUTE_PATHS_ONLY
CompileTypeScript:
Skipping target "CompileTypeScript" because it has no outputs.
CoreCompile:
C:\Users\buildguest\.dnx\runtimes\dnx-clr-win-x86.1.0.0-beta6\bin\dnx.exe --appbase "C:\a\dce2e497\Root\TestApi.Api" "C:\Users\buildguest\.dnx\runtimes\dnx-clr-win-x86.1.0.0-beta6\bin\lib\Microsoft.Framework.PackageManager\Microsoft.Framework.PackageManager.dll" pack "C:\a\dce2e497\Root\TestApi.Api" --configuration Release --out "..\artifacts\bin\TestApi.Api"
Microsoft .NET Development Utility CLR-x86-1.0.0-beta6-12256
Building TestApi.Api for DNX,Version=v4.5.1
Using Project dependency TestApi.Api 1.0.0
Source: C:\a\dce2e497\Root\TestApi.Api\project.json
Unable to resolve dependency Microsoft.AspNet.Server.IIS 1.0.0-beta6
TestApi.Api\Startup.cs(5,17): Error CS0234: The type or namespace name 'AspNet' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
2>C:\a\dce2e497\Root\TestApi.Api\Startup.cs(5,17): DNX,Version=v4.5.1 error CS0234: The type or namespace name 'AspNet' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) [C:\a\dce2e497\Root\TestApi.Api\TestApi.Api.xproj]
TestApi.Api\Startup.cs(6,17): Error CS0234: The type or namespace name 'AspNet' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
2>C:\a\dce2e497\Root\TestApi.Api\Startup.cs(6,17): DNX,Version=v4.5.1 error CS0234: The type or namespace name 'AspNet' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) [C:\a\dce2e497\Root\TestApi.Api\TestApi.Api.xproj]
并且当你需要通过邮寄或者像这样得到服务器中的数据时调用该函数
package com.yubraj.sample.datamanager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import com.yubaraj.sample.utilities.GeneralUtilities;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by yubraj on 7/30/15.
*/
public class ServerRequestHandler {
private static final String TAG = "Server Request";
OnServerRequestComplete listener;
public ServerRequestHandler (){
}
public void doServerRequest(HashMap<String, String> parameters, String url, int requestType, OnServerRequestComplete listener){
debug("ServerRequest", "server request called, url = " + url);
if(listener != null){
this.listener = listener;
}
try {
new BackgroundDataSync(getPostDataString(parameters), url, requestType).execute();
debug(TAG , " asnyc task called");
} catch (Exception e) {
e.printStackTrace();
}
}
public void doServerRequest(HashMap<String, String> parameters, String url, int requestType){
doServerRequest(parameters, url, requestType, null);
}
public interface OnServerRequestComplete{
void onSucess(Bundle bundle);
void onFailed(int status_code, String mesage, String url);
}
public void setOnServerRequestCompleteListener(OnServerRequestComplete listener){
this.listener = listener;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
class BackgroundDataSync extends AsyncTask<String, Void , String>{
String params;
String mUrl;
int request_type;
public BackgroundDataSync(String params, String url, int request_type){
this.mUrl = url;
this.params = params;
this.request_type = request_type;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... urls) {
debug(TAG, "in Background, urls = " + urls.length);
HttpURLConnection connection;
debug(TAG, "in Background, url = " + mUrl);
String response = "";
switch (request_type) {
case 1:
try {
connection = iniitializeHTTPConnection(mUrl, "POST");
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(params);
writer.flush();
writer.close();
os.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
/* String line;
BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}*/
response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
} else {
response = "";
}
} catch (IOException e) {
e.printStackTrace();
}
break;
case 0:
connection = iniitializeHTTPConnection(mUrl, "GET");
try {
if (connection.getResponseCode() == connection.HTTP_OK) {
response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
}
} catch (Exception e) {
e.printStackTrace();
response = "";
}
break;
}
return response;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(TextUtils.isEmpty(s) || s.length() == 0){
listener.onFailed(DbConstants.NOT_FOUND, "Data not found", mUrl);
}
else{
Bundle bundle = new Bundle();
bundle.putInt(DbConstants.STATUS_CODE, DbConstants.HTTP_OK);
bundle.putString(DbConstants.RESPONSE, s);
bundle.putString(DbConstants.URL, mUrl);
listener.onSucess(bundle);
}
//System.out.println("Data Obtained = " + s);
}
private HttpURLConnection iniitializeHTTPConnection(String url, String requestType) {
try {
debug("ServerRequest", "url = " + url + "requestType = " + requestType);
URL link = new URL(url);
HttpURLConnection conn = (HttpURLConnection) link.openConnection();
conn.setRequestMethod(requestType);
conn.setDoInput(true);
conn.setDoOutput(true);
return conn;
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
private String getDataFromInputStream(InputStreamReader reader){
String line;
String response = "";
try {
BufferedReader br = new BufferedReader(reader);
while ((line = br.readLine()) != null) {
response += line;
debug("ServerRequest", "response length = " + response.length());
}
}
catch (Exception e){
e.printStackTrace();
}
return response;
}
private void debug(String tag, String string) {
Log.d(tag, string);
}
}
现在已经完成了。享受!!!如果发现任何问题请注释。
答案 6 :(得分:0)
HTTP授权在GET和POST请求之间没有区别,所以我首先假设其他错误。我建议使用java.net.Authorization类,而不是直接设置Authorization标头,但我不确定它是否解决了你的问题。也许您的服务器以某种方式配置为要求与“基本”不同的授权方案用于发布请求?
答案 7 :(得分:0)
我正在查看有关如何执行POST请求的信息。我需要指定mi请求是POST请求,因为我正在使用仅使用POST方法的RESTful Web服务,如果请求没有发布,当我尝试执行请求时,我收到HTTP错误405。我保证我的代码在下一步做错了:我在我的Web服务中创建一个通过GET请求调用的方法,并指出我的应用程序使用该Web服务方法并且它可以工作。 我的代码是下一个:
URL server = null;
URLConnection conexion = null;
BufferedReader reader = null;
server = new URL("http://localhost:8089/myApp/resources/webService");
conexion = server.openConnection();
reader = new BufferedReader(new InputStreamReader(server.openStream()));
System.out.println(reader.readLine());