我使用了Spring的RestTemplate HTTP客户端,它运行得很好。也许可以使用该客户端。
public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); HttpHeaders hh = new HttpHeaders(); hh.setContentType(MediaType.APPLICATION_JSON); hh.set(AUTHORIZATION, "Basic Og=="); hh.setCacheControl("no-cache"); HttpEntity he = new HttpEntity(hh); String url = "https://rest.cgorders.com/api/orders/order?access_token=97484431a4525ed2b294b699a3d2f202&id=15755354"; Map results = restTemplate.exchange(url, HttpMethod.GET, he, Map.class).getBody(); //this also worked and is a lot less code //Map results = restTemplate.getForObject("https://rest.cgorders.com/api/orders/order?access_token=97484431a4525ed2b294b699a3d2f202&id=15755354", Map.class); System.out.println(gson.toJson(results)); }
以下是您要复制的导入。
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.Map; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import static org.springframework.http.HttpHeaders.AUTHORIZATION; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.web.client.RestTemplate;
以下适用于我。你需要改变什么来让它按你想要的方式工作?
public class GetRequest { public static void main( String[] args ) { System.out.println( new GetRequest().get( "" ) ); } public String get( String search ) { try { URL url = new URL( "https://rest.cgorders.com/api/orders/order?access_token=97484431a4525ed2b294b699a3d2f202&id=15755354" ); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod( "GET" ); conn.setRequestProperty( "Accept", "application/json" ); conn.connect(); BufferedReader br = new BufferedReader( new InputStreamReader( conn.getInputStream(), "UTF-8" ) ); StringBuilder sb = new StringBuilder( 2048 ); for( String line; (line = br.readLine()) != null; ) { sb.append( line ); } conn.disconnect(); return sb.toString(); } catch( IOException ex ) { Logger.getLogger( Pixabay.class.getName() ).log( Level.SEVERE, null, ex ); return ex.toString(); } } }