通过Java代码调用Rest API时收到空白响应,但通过Postman运行正常。

huangapple go评论80阅读模式
英文:

Getting blank response on invoking Rest API thur java code but thur postman working fine

问题

在Postman中,我正在调用一个RestAPI。我已经选择了基本身份验证并传递了用户名和密码。它正在工作。我收到了响应。但是当我通过Java代码运行它并使用Base64编码进行身份验证时,我收到了空白响应。下面附有截图:

通过Postman调用RestAPI

用于执行相同操作的Java代码如下:

public static String doPOSTCall(String postUrl, String authorization, JSONObject jo) throws Exception {
    String output = "";
    CloseableHttpClient httpClientPO = (HttpClients.createDefault());
    HttpPost httpPostPO = new HttpPost(postUrl);

    String auth = "ts_impl" + ":" + "Oracle@123";

    byte[] encodedAuth = Base64.encodeBase64(
              auth.getBytes(StandardCharsets.ISO_8859_1));
    String authHeader = "Basic " + new String(encodedAuth);
    httpPostPO.setHeader(HttpHeaders.AUTHORIZATION, authHeader);

    httpPostPO.setHeader("content-type", "application/json");
    StringWriter out = new StringWriter();
    jo.writeJSONString(out);
    String reqJsonString = out.toString();

    System.out.println("json2 is " + reqJsonString);
    StringEntity entityPO = new StringEntity(reqJsonString);

    System.out.println("Request : " + httpPostPO);

    httpPostPO.setEntity(entityPO);

    HttpResponse responsePO = httpClientPO.execute(httpPostPO);
    HttpEntity entityFromResponse = responsePO.getEntity();

    if (entityFromResponse != null) {
        output = EntityUtils.toString(responsePO.getEntity());
        System.out.println(output);
    }

    return output;
}

希望这有助于您解决问题。

英文:

In postman, I am calling a RestAPI. I have selected Basic Auth and passing username and password. It is working. I am getting response. But when I run it thru Java code and do authentication using Base64 encoding, I am getting blank response. Snapshots are attached below:

Calling RestAPI thru Postman

Java code to do the same is below:

public static String doPOSTCall(String postUrl, String authorization, JSONObject jo) throws Exception {
		String output = "";
		CloseableHttpClient httpClientPO = (HttpClients.createDefault());
		HttpPost httpPostPO = new HttpPost(postUrl);

		String auth = "ts_impl" + ":" + "Oracle@123";

		byte[] encodedAuth = Base64.encodeBase64(
				  auth.getBytes(StandardCharsets.ISO_8859_1));
				String authHeader = "Basic " + new String(encodedAuth);
				httpPostPO.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
		
		
		//httpPostPO.setHeader("Authorization", authorization);
		httpPostPO.setHeader("content-type", "application/json");
		StringWriter out = new StringWriter();
		jo.writeJSONString(out);
		String reqJsonString = out.toString();

		System.out.println("json2 is " + reqJsonString);
		StringEntity entityPO = new StringEntity(reqJsonString);

		System.out.println("Request : " + httpPostPO);

		httpPostPO.setEntity(entityPO);

		HttpResponse responsePO = httpClientPO.execute(httpPostPO);
		HttpEntity entityFromResponse = responsePO.getEntity();

		if (entityFromResponse != null) {

			output = EntityUtils.toString(responsePO.getEntity());
			System.out.println(output);
		}

		return output;
	}

答案1

得分: 0

你可以像这样创建已编码的标头:

String authHeader = "Basic " + Base64.getEncoder().encodeToString(auth.getBytes());
英文:

You can to create the encoded header like this:

String authHeader = "Basic " + Base64.getEncoder().encodeToString(auth.getBytes());

答案2

得分: 0

以下是您要翻译的内容:

使用简单的REST客户端,您可以尝试以下代码:

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;

public class RestClient {

    public static void main(String args[]) {

        String url = "在此处填入您的URL";
        String name = "用户名";
        String password = "密码";
        String authorization = name + ":" + password;

        JSONObject jo; // 创建您的对象
        // 对jo对象进行必要的操作,提供数据等等

        String response = doPOSTCall(url, authorization, jo);
        System.out.println("响应: " + response);
    }

    public static String doPOSTCall(String postUrl, String authorization, JSONObject jo) throws Exception {

        // 认证部分
        String authStringEnc = new BASE64Encoder().encode(authorization.getBytes());
        System.out.println("Base64编码的认证字符串: " + authStringEnc);

        // JSON转为字符串
        StringWriter out = new StringWriter();
        jo.writeJSONString(out);
        String reqJsonString = out.toString();
        System.out.println("json2是 " + reqJsonString);

        // 发起REST调用
        Client restClient = Client.create();
        WebResource webResource = restClient.resource(url);
        ClientResponse resp = webResource.accept("application/json")
                                         .header("Authorization", "Basic " + authStringEnc)
                                         .post(ClientResponse.class, reqJsonString);

        // 验证响应
        if (resp.getStatus() != 200) {
            System.err.println("无法连接到服务器");
        }

        String output = resp.getEntity(String.class);
        return output;
    }
}

更新:

Maven依赖:

<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-client -->
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.19.4</version>
</dependency>
英文:

Use a simple REST Client, You can try the below code :

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration; 
public class RestClient {
public static void main(String args[]){
String url = &quot;Give-Your-URL-here&quot;;
String name = &quot;username&quot;;
String password = &quot;password&quot;;
String authorization = name + &quot;:&quot; + password;
JSONObject jo; // Create your Object 
// Do the necessary stuffs with the jo object, feeding data etc.
String response = doPOSTCall(url, String authorization, JSONObject jo);        
System.out.println(&quot;response: &quot;+response);
}
public static String doPOSTCall(String postUrl, String authorization, JSONObject jo) throws Exception {
// Authentication Part
String authStringEnc = new BASE64Encoder().encode(authorization.getBytes());
System.out.println(&quot;Base64 encoded auth string: &quot; + authStringEnc);
// JSON to String
StringWriter out = new StringWriter();
jo.writeJSONString(out);
String reqJsonString = out.toString();    
System.out.println(&quot;json2 is &quot; + reqJsonString);
//REST calling
Client restClient = Client.create();
WebResource webResource = restClient.resource(url);
ClientResponse resp = webResource.accept(&quot;application/json&quot;)
.header(&quot;Authorization&quot;, &quot;Basic &quot; + authStringEnc)
.post(ClientResponse.class, reqJsonString);
// Response Verification
if(resp.getStatus() != 200){
System.err.println(&quot;Unable to connect to the server&quot;);
}
String output = resp.getEntity(String.class);
return output;
}
}

Update :

Maven Dependencies :    
&lt;!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-client --&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.sun.jersey&lt;/groupId&gt;
&lt;artifactId&gt;jersey-client&lt;/artifactId&gt;
&lt;version&gt;1.19.4&lt;/version&gt;
&lt;/dependency&gt;

答案3

得分: 0

开始工作。问题是我在代码中使用了 HTTP 链接,而实际上应该使用 HTTPS 链接。

英文:

Started working. The problem was that I was using http link in the code, where as it should have been https.

huangapple
  • 本文由 发表于 2020年8月24日 18:34:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63559339.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定